package cn.danger.com.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatImageView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Map;

import cn.danger.com.fragment.FragmentController;
import cn.danger.com.fragment.calender.CalendarFragment;
import cn.danger.com.fragment.memo.MemoFragment;
import cn.danger.com.fragment.schedule.ScheduleFragment;
import cn.danger.com.util.DensityUtil;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.widget.MyPopupWindow;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private TextView bar_title_textView;
    private AppCompatButton edit_button;
    private AppCompatImageView today_imageView;
    //日程TAB
    private RelativeLayout schedule_tab;
    private ImageView schedule_tab_image;
    private TextView schedule_tab_title;
    //备忘录TAB
    private RelativeLayout memo_tab;
    private ImageView memo_tab_image;
    private TextView memo_tab_title;
    //添加TAB
    private ImageView add_tab_image;
    //日历TAB
    private RelativeLayout calendar_tab;
    private ImageView calendar_tab_image;
    private TextView calendar_tab_title;
    //用户TAB
    private RelativeLayout user_tab;
    private ImageView user_tab_image;
    private TextView user_tab_title;

    private LinearLayout bottom_bar_layout;

    private FragmentController controller;

    private static final int REQUEST_CODE = 1;

    private MyPopupWindow popupWindow;

    private float alpha = 1.0f;

    private MyReceiver receiver;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    ((ScheduleFragment) controller.getFragment(0)).update();
                    ((MemoFragment) controller.getFragment(1)).update();
                    ((CalendarFragment) controller.getFragment(2)).update();
                    break;
                case 2:
                    backgroundAlpha((float) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //检查是否授权，若没有，则申请读写权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
        } else {
            bindView();
            bindEvent();

            controller = FragmentController.getInstance(this, R.id.container, handler);
            controller.showFragment(0);
        }
    }

    @Override
    public void bindView() {
        bottom_bar_layout = (LinearLayout) findViewById(R.id.bottom_bar_layout);
        bar_title_textView = (TextView) findViewById(R.id.bar_title_textView);
        edit_button = (AppCompatButton) findViewById(R.id.edit_button);
        today_imageView = (AppCompatImageView) findViewById(R.id.today_imageView);

        schedule_tab = (RelativeLayout) findViewById(R.id.schedule_tab);
        schedule_tab_image = (ImageView) findViewById(R.id.schedule_tab_image);
        schedule_tab_title = (TextView) findViewById(R.id.schedule_tab_title);

        memo_tab = (RelativeLayout) findViewById(R.id.memo_tab);
        memo_tab_image = (ImageView) findViewById(R.id.memo_tab_image);
        memo_tab_title = (TextView) findViewById(R.id.memo_tab_title);

        add_tab_image = (ImageView) findViewById(R.id.add_tab_image);

        calendar_tab = (RelativeLayout) findViewById(R.id.calendar_tab);
        calendar_tab_image = (ImageView) findViewById(R.id.calendar_tab_image);
        calendar_tab_title = (TextView) findViewById(R.id.calendar_tab_title);

        user_tab = (RelativeLayout) findViewById(R.id.user_tab);
        user_tab_image = (ImageView) findViewById(R.id.user_tab_image);
        user_tab_title = (TextView) findViewById(R.id.user_tab_title);

        FileCacheService service = new FileCacheService(this);
        Map<String, Object> map = (Map<String, Object>) service.getSharePreference("setting");
        if (map.get("show_finished_event") == null) {
            new FileCacheService(this).defaultSetting();
        }

        popupWindow = new MyPopupWindow(this);
        popupWindow.setItem1TextView("添加日程");
        popupWindow.setItem2TextView("添加备忘录");

        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter("update_ui");
        registerReceiver(receiver, filter);
    }

    @Override
    public void bindEvent() {
        schedule_tab.setOnClickListener(this);
        memo_tab.setOnClickListener(this);
        add_tab_image.setOnClickListener(this);
        calendar_tab.setOnClickListener(this);
        user_tab.setOnClickListener(this);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (alpha < 1.0f) {
                            try {
                                Thread.sleep(4);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = Message.obtain();
                            message.what = 2;
                            alpha += 0.01f;
                            message.obj = alpha;
                            handler.sendMessage(message);
                        }
                    }
                }).start();
            }
        });

        popupWindow.setOnClickItem1Listener(new MyPopupWindow.OnClickItem1Listener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(MainActivity.this, CommonActivity.class);
                intent.putExtra("target", "add_schedule");
                startActivity(intent);
                popupWindow.dismiss();
            }
        });

        popupWindow.setOnClickItem2Listener(new MyPopupWindow.OnClickItem2Listener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(MainActivity.this, CommonActivity.class);
                intent.putExtra("target", "add_memo");
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "请求读写权限失败", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                } else {
                    bindView();
                    bindEvent();

                    controller = FragmentController.getInstance(this, R.id.container, handler);
                    controller.showFragment(0);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.schedule_tab:
                reset();
                bar_title_textView.setText(getResources().getString(R.string.schedule));
                edit_button.setVisibility(View.GONE);
                today_imageView.setVisibility(View.GONE);
                schedule_tab_image.setImageResource(R.mipmap.schedule);
                schedule_tab_title.setTextColor(getResources().getColor(R.color.colorPrimary));
                controller.showFragment(0);
                break;
            case R.id.memo_tab:
                reset();
                bar_title_textView.setText(getResources().getString(R.string.memo));
                edit_button.setVisibility(View.VISIBLE);
                memo_tab_image.setImageResource(R.mipmap.memo);
                today_imageView.setVisibility(View.GONE);
                memo_tab_title.setTextColor(getResources().getColor(R.color.colorPrimary));
                controller.showFragment(1);
                break;
            case R.id.add_tab_image:
                popupWindow.setAnimationStyle(R.style.popupwindow_anim);
                popupWindow.showAsDropDown(bottom_bar_layout, 0, -DensityUtil.dip2px(this, 50));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (alpha > 0.5f) {
                            try {
                                Thread.sleep(4);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = Message.obtain();
                            message.what = 2;
                            alpha -= 0.01f;
                            message.obj = alpha;
                            handler.sendMessage(message);
                        }
                    }
                }).start();
                break;
            case R.id.calendar_tab:
                reset();
                bar_title_textView.setText(getResources().getString(R.string.calendar));
                edit_button.setVisibility(View.GONE);
                today_imageView.setVisibility(View.VISIBLE);
                calendar_tab_image.setImageResource(R.mipmap.calendar);
                calendar_tab_title.setTextColor(getResources().getColor(R.color.colorPrimary));
                controller.showFragment(2);
                break;
            case R.id.user_tab:
                reset();
                bar_title_textView.setText(getResources().getString(R.string.user));
                today_imageView.setVisibility(View.GONE);
                edit_button.setVisibility(View.GONE);
                user_tab_image.setImageResource(R.mipmap.user);
                user_tab_title.setTextColor(getResources().getColor(R.color.colorPrimary));
                controller.showFragment(3);
                break;
            default:
                break;
        }
    }

    /**
     * 重置TAB状态
     */
    private void reset() {
        schedule_tab_image.setImageResource(R.mipmap.schedule_);
        schedule_tab_title.setTextColor(getResources().getColor(R.color.tab_title_color));
        memo_tab_image.setImageResource(R.mipmap.memo_);
        memo_tab_title.setTextColor(getResources().getColor(R.color.tab_title_color));
        calendar_tab_image.setImageResource(R.mipmap.calendar_);
        calendar_tab_title.setTextColor(getResources().getColor(R.color.tab_title_color));
        user_tab_image.setImageResource(R.mipmap.user_);
        user_tab_title.setTextColor(getResources().getColor(R.color.tab_title_color));
    }

    private void backgroundAlpha(float alpha) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = alpha;
        getWindow().setAttributes(layoutParams);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    public AppCompatButton getEditButton() {
        return edit_button;
    }

    public TextView getBarTitleTextView() {
        return bar_title_textView;
    }

    public AppCompatImageView getTodayImageView() {
        return today_imageView;
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("danger", "收到了........");
            handler.sendEmptyMessage(1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}